package com.hemaapp.yjnh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.ViewPagerFragment;
import com.hemaapp.yjnh.activity.BuyerOrderDetailActivity;
import com.hemaapp.yjnh.activity.BuyerCustomOrderDetailActivity;
import com.hemaapp.yjnh.activity.FarmerOrderDetailActivity;
import com.hemaapp.yjnh.activity.FriendPayDetailActivity;
import com.hemaapp.yjnh.activity.LaokeDetailActivity;
import com.hemaapp.yjnh.activity.MyFarmerActivity;
import com.hemaapp.yjnh.activity.NoticeInfoActivity;
import com.hemaapp.yjnh.adapter.NoticeAdapter;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.chat.ChatPrivateActivity;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.Notice;
import com.hemaapp.yjnh.bean.User;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 类描述：通用消息列表
 * 创建人：GuiyouZhang
 * 创建时间：2016/8/2 20:37
 * 修改备注：
 */
public class NoticeListFragment extends ViewPagerFragment {

    private RefreshLoadmoreLayout refreshLoadmoreLayout;
    private RecyclerView recyclerView;

    private User user;
    private int page = 0;
    private NoticeAdapter adapter;
    private String keytype = "0";//1系统通知；2评论回复；3聊天人员列表页
    private ArrayList<Notice> datas = new ArrayList<>();
    private Notice curNotice;//当前操作的凶啊系通知

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_viewpager_refresh_recycler);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            keytype = savedInstanceState.getString("keytype");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("keytype", keytype);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void fetchData() {
        getNetWorker().noticeList(user.getToken(), keytype, page+"");
    }

    public void setNoticetype(String noticetype) {
        this.keytype = noticetype;
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask hemaNetTask) {
        BaseHttpInformation info = (BaseHttpInformation) hemaNetTask.getHttpInformation();
        switch (info) {
            case CLIENT_GET:
            case NOTICE_SAVEOPERATE:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask hemaNetTask) {
        BaseHttpInformation info = (BaseHttpInformation) hemaNetTask.getHttpInformation();
        switch (info) {
            case CLIENT_GET:
            case NOTICE_SAVEOPERATE:
                if (!isHidden())
                    cancelProgressDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask hemaNetTask, HemaBaseResult hemaBaseResult) {
        BaseHttpInformation info = (BaseHttpInformation) hemaNetTask
                .getHttpInformation();
        switch (info) {
            case NOTICE_LIST:
                String page = hemaNetTask.getParams().get("page");
                HemaPageArrayResult<Notice> iResult = (HemaPageArrayResult<Notice>) hemaBaseResult;
                if ("0".equals(page)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    refreshLoadmoreLayout.setLoadmoreable(true);
                    datas.clear();
                    datas.addAll(iResult.getObjects());
                } else {// 更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (iResult.getObjects().size() > 0) {
                        datas.addAll(iResult.getObjects());
                    } else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                    }
                }
                refreshData();
                break;
            case NOTICE_SAVEOPERATE:
                String operate = hemaNetTask.getParams().get("operatetype");
                if (operate.equals("1")) {//置为已读
                    for (Notice item : datas) {
                        if (item.getId().equals(curNotice.getId())) {
                            item.setLooktype("2");
                            break;
                        }
                    }
                }else if (operate.equals("2")) {//全部置为已读
                    for (Notice item : datas) {
                        item.setLooktype("2");
                    }
                }else if (operate.equals("3")) {//删除单条
                    datas.remove(curNotice);
                }else if (operate.equals("4")) {//删除全部 (此处服务器会根据keytype智能判断并处理)
                    datas.clear();
                }else if (operate.equals("5")) {//同意好友申请

                }
                refreshData();
                curNotice = null;
                getNetWorker().clientLogin();//执行重新登录，让所有显示有新消息的地方更新
                break;
            case CLIENT_GET:
                HemaArrayResult<ClientDetails> uResult = (HemaArrayResult<ClientDetails>) hemaBaseResult;
                ClientDetails client = uResult.getObjects().get(0);
                if (client == null) {
                    showTextDialog("获取对方信息失败!");
                    break;
                }
                Intent itChat = new Intent(getActivity(), ChatPrivateActivity.class);
                itChat.putExtra("to_client_id", client.getId());
                itChat.putExtra("to_nickname", client.getNickname());
                itChat.putExtra("to_avatar", client.getAvatar());
                startActivity(itChat);
                break;
            case CLIENT_LOGIN:
                User user = ((HemaArrayResult<User>) hemaBaseResult).getObjects().get(0);
                BaseApplication.getInstance().setUser(user);
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.USER);
                msg.setUser(user);
                EventBus.getDefault().post(msg);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask hemaNetTask, HemaBaseResult hemaBaseResult) {
        BaseHttpInformation info = (BaseHttpInformation) hemaNetTask
                .getHttpInformation();
        switch (info) {
            case NOTICE_LIST:
                XtomToastUtil.showShortToast(getActivity(), "获取消息失败," + hemaBaseResult.getMsg());
                if (page == 0)
                    refreshLoadmoreLayout.refreshFailed();
                else
                    refreshLoadmoreLayout.loadmoreFailed();
                break;
            case NOTICE_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败," + hemaBaseResult.getMsg());
                break;
            case CLIENT_GET:
                XtomToastUtil.showShortToast(getActivity(), "获取对方信息失败," + hemaBaseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask hemaNetTask, int i) {
        BaseHttpInformation info = (BaseHttpInformation) hemaNetTask
                .getHttpInformation();
        switch (info) {
            case NOTICE_LIST:
                XtomToastUtil.showShortToast(getActivity(), "取消消息失败,请稍后再试");
                if (page == 0)
                    refreshLoadmoreLayout.refreshFailed();
                else
                    refreshLoadmoreLayout.loadmoreFailed();
                break;
            case NOTICE_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败,请稍后再试");
                break;
            case CLIENT_GET:
                XtomToastUtil.showShortToast(getActivity(), "获取对方信息失败,请稍后再试");
                break;
        }
    }

    private void refreshData() {
        if (adapter == null) {
            adapter = new NoticeAdapter(getActivity(), datas);
            adapter.setItemClickListener(new NoticeAdapter.OnNoticeClickListener() {
                @Override
                public void onClickListener(int position) {
                    curNotice = datas.get(position);
                    if (user != null && curNotice.getLooktype().equals("1")) {//如果是未读消息，就置为已读
                        getNetWorker().noticeOperate(user.getToken(), curNotice.getId(), curNotice.getKeytype(), "0", "1");
                    }
                    String keytype = curNotice.getKeytype();
                    String keyid = curNotice.getKeyid();
                    if (keytype.equals("1")) {
                        Intent itSys = new Intent(getActivity(), NoticeInfoActivity.class);
                        itSys.putExtra("notice", curNotice);
                        startActivity(itSys);
                    }else if (keytype.equals("2")) {
                        Intent itBlog = new Intent(getActivity(), LaokeDetailActivity.class);
                        itBlog.putExtra("blog_id", keyid);
                        startActivity(itBlog);
                    }else if (keytype.equals("3")) {
                        //先去获取聊天对方的个人信息
                        getNetWorker().clientGet("", keyid);
                    }else if (keytype.equals("6")) {
                        //跳转SellerOrderDtlActivity
                        Intent itSeller = new Intent(getActivity(), FarmerOrderDetailActivity.class);
                        itSeller.putExtra("order_id", keyid);
                        startActivity(itSeller);
                    }else if (keytype.equals("7")) {
                        //跳转FriendPayDtlActivity
                        Intent itFriend = new Intent(getActivity(), FriendPayDetailActivity.class);
                        itFriend.putExtra("order_id", keyid);
                        startActivity(itFriend);
                    }else if (keytype.equals("8")) {
                        //跳转BuyerOrderDtlActivity
                        Intent itBuyer = new Intent(getActivity(), BuyerOrderDetailActivity.class);
                        itBuyer.putExtra("order_id", keyid);
                        startActivity(itBuyer);
                    }else if (keytype.equals("9")) {//9：买家定制订单通知； 
                        Intent itCustom = new Intent(getActivity(), BuyerCustomOrderDetailActivity.class);
                        itCustom.putExtra("order_id", keyid);
                        startActivity(itCustom);
                    }else if (keytype.equals("10")) {//卖家定制订单通知；
                        if (user != null && user.getRole().equals("1")) {//如果是田家
                            Intent itFarmer = new Intent(getActivity(), MyFarmerActivity.class);
                            itFarmer.putExtra("start_page", 2);
                            startActivity(itFarmer);
                        }else {
                            return;
                        }
                    }
                }

                @Override
                public void onLongClickListener(int position) {
                    curNotice = datas.get(position);
                    if (user != null) {//
                        getNetWorker().noticeOperate(user.getToken(), curNotice.getId(), curNotice.getKeytype(), "sb", "3");
                    }
                }
            });
            recyclerView.setAdapter(adapter);
        }else
            adapter.notifyDataSetChanged();
    }

    @Override
    protected void findView() {
        refreshLoadmoreLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    protected void setListener() {
        refreshLoadmoreLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().noticeList(user.getToken(), keytype, page+"");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().noticeList(user.getToken(), keytype, page+"");
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    public void clearAll() {
        getNetWorker().noticeOperate(user.getToken(),
                "无", keytype, "0", "4");
    }

    public void readAll() {
        getNetWorker().noticeOperate(user.getToken(),
                "无", keytype, "0", "2");
    }
}
